package com.dylan.历史.java8.StreamAPI;

import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Created by Dylan on 2018/7/25.
 */
public class 并行Stream {

    public static void main(String[] args) {
        // 使用 parallel() 和 parallelStream() 创建并行流
        // 只要在终止方法执行时,流处于并行模式,那么所有延迟执行的流操作都会被并行执行.即在终止操作执行前执行parallel()方法,
        // 则终止方法前的所有流都会并行执行
        IntStream stream1 = IntStream.range(0, 100).parallel();
        Stream stream2 = Collections.nCopies(100, new Object()).parallelStream();

        // 确保传递给并行流操作的函数是线程安全的,下面是非线程安全的,每次执行结果不一致
        final int[] count = {0};
        IntStream.range(0, 1000000000).parallel().forEach(s -> count[0]++);
//        System.out.println(count[0]);

        // 并发的进行分组操作
        Map<Integer, List<Integer>> map1 = IntStream.range(0, 10000).boxed().parallel().collect(Collectors.groupingByConcurrent(i -> i / 100));
//        for (Map.Entry<Integer, List<Integer>> entry : map1.entrySet()) {
//            System.out.println(entry.getKey() + ":" + entry.getValue());
//        }


    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
